<?php

namespace App\Imports\Batch;

use Illuminate\Support\Facades\Cache;

class SourceCode
{
    public $str_map = ['A', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    public $cache;

    public function __construct()
    {
        $this->cache = Cache::store('file');
    }

    /**
     * 检测溯源码是否正确
     * @param $source_code
     * @return bool
     */
    public function check($source_code)
    {
        $payload = substr($source_code, 0, -3);
        return $source_code == $this->sign($payload);
    }

    /**
     * 创建溯源码
     * @param bool $char
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function build($char = false)
    {
        if ($char) {
            $main_char = $this->str_map[date('i') % 25];
        } else {
            $main_char = '';
        }
        $key = $main_char . date('ymdHi');
        if (!$this->cache->has($key)) {
            $this->cache->set($key, 1);
        }
        $new = $this->cache->increment($key, 1);
        return $this->sign($main_char . date('ymdHi') . $new);
    }

    /**
     * 进行签名
     * @param $str
     * @return string
     */
    public function sign($str)
    {
        $key1 = crc32($str);
        $key2 = crc32($key1);
        $key3 = crc32($key2);

        $k_key2 = mb_strlen($key2) ?: 1;
        $k_key3 = mb_strlen($key3) ?: 1;

        return $str . substr($key1, 1, 1) . substr($key2, $key2 % $k_key2, 1) . substr($key3, $key3 % $k_key3, 1);
    }
}
